package ory

import (
	"context"
	"fmt"
	client "github.com/ory/kratos-client-go"
	"os"
)

func NewKeto(ctx context.Context, url string) *Kratos {
	configuration := client.NewConfiguration()
	configuration.Servers = []client.ServerConfiguration{
		{
			URL: url,
		},
	}

	return &Kratos{
		ctx:    ctx,
		client: client.NewAPIClient(configuration),
	}
}

// Use this context to access Ory APIs which require an Ory API Key.
var namespace = "Blog"
var object = "secret_post"
var relation = "view"
var subjectId = "Bob"

func main() {
	payload := ory.CreateRelationshipBody{
		Namespace: &namespace,
		Object:    &object,
		Relation:  &relation,
		SubjectId: &subjectId,
	}
	configuration := ory.NewConfiguration()
	configuration.Servers = []ory.ServerConfiguration{
		{
			URL: "http://127.0.0.1:4467", // Write API
		},
	}
	writeClient := ory.NewAPIClient(configuration)
	_, r, err := writeClient.RelationshipApi.CreateRelationship(context.Background()).CreateRelationshipBody(payload).Execute()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
		panic("Encountered error: " + err.Error())
	}
	fmt.Println("Successfully created tuple")
	configuration.Servers = []client.ServerConfiguration{
		{
			URL: "http://127.0.0.1:4466", // Read API
		},
	}
	readClient := client.NewAPIClient(configuration)

	check, r, err := readClient.PermissionApi.CheckPermission(context.Background()).
		Namespace(*&namespace).
		Object(*&object).
		Relation(*&relation).
		SubjectId(*&subjectId).Execute()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
		panic("Encountered error: " + err.Error())
	}
	if check.Allowed {
		fmt.Println(*&subjectId + " can " + *&relation + " the " + *&object)
	}
}

import { Namespace, SubjectSet, Context } from "@ory/keto-namespace-types"

class User implements Namespace { }

class Blog implements Namespace {
related: {
viewers: User[]
}

permits = {
view: (ctx: Context): boolean =>
this.related.viewers.includes(ctx.subject)
}
}